package cn.edu.nwpu.warehousemanagement.service.impl;

import cn.edu.nwpu.warehousemanagement.dao.FreightRepository;
import cn.edu.nwpu.warehousemanagement.dao.ShelfRepository;
import cn.edu.nwpu.warehousemanagement.pojo.Result;
import cn.edu.nwpu.warehousemanagement.pojo.Shelf;
import cn.edu.nwpu.warehousemanagement.service.ShelfService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author ljl
 * Shelf 的服务实现，负责处理货架相关业务逻辑
 */
@Service
public class ShelfServiceImpl implements ShelfService {

    @Resource
    private ShelfRepository shelfRepository;

    // 新增FreightRepository依赖
    @Resource
    private FreightRepository freightRepository;

    /**
     * 创建一个新的货架
     *
     * @param shelf 要保存的货架对象
     * @return 成功返回创建后的货架对象
     */
    @Override
    public Result<String> createShelf(Shelf shelf) {
        shelfRepository.save(shelf);
        return Result.success("created");
    }

    /**
     * 根据 ID 更新已有的货架信息
     *
     * @param shelf 新的货架信息
     * @return 成功返回更新后的货架对象，失败返回错误信息
     */
    @Override
    public Result<String> updateShelf(Shelf shelf) {
        Optional<Shelf> optionalShelf = shelfRepository.findByIdAndDeletedFalse(shelf.getId());
        if (optionalShelf.isEmpty()) {
            return Result.error("货架不存在或已被删除");
        }

        Shelf existing = optionalShelf.get();
        existing.setName(shelf.getName());
        existing.setLocation(shelf.getLocation());
        existing.setCapacity(shelf.getCapacity());
        existing.setShelfStatus(shelf.getShelfStatus());

        Shelf updated = shelfRepository.save(existing);
        return Result.success("updated");
    }

    /**
     * 根据 ID 软删除货架
     *
     * @param id 要删除的货架ID
     * @return 成功返回空，失败返回错误信息
     */
    @Override
    public Result<Void> deleteShelf(Long id) {
        Optional<Shelf> optionalShelf = shelfRepository.findByIdAndDeletedFalse(id);
        if (optionalShelf.isEmpty()) {
            return Result.error("货架不存在或已被删除");
        }

        // ========== 新增货物存在性检查 ==========
        long freightCount = freightRepository.countByShelfIdAndDeletedFalse(id);
        if (freightCount > 0) {
            return Result.error("货架上存在未移走的货物，无法删除");
        }
        // ========== 检查结束 ==========

        Shelf shelf = optionalShelf.get();
        shelf.setDeleted(true);
        shelfRepository.save(shelf);
        return Result.success();
    }

    @Override
    public Result<Shelf> getShelfById(Long id) {
        Optional<Shelf> optionalShelf = shelfRepository.findByIdAndDeletedFalse(id);
        return optionalShelf.map(Result::success).orElseGet(() -> Result.error("货架不存在或已被删除"));
    }

    @Override
    public Result<List<Shelf>> getAllShelves() {
        List<Shelf> shelves = shelfRepository.findAllByDeletedFalse();
        return Result.success(shelves);
    }
}